<?php

use Doraemon\tools\HhzEnv;

/**
 * @name Bootstrap
 * @author luomo-l540\luomo
 * @desc 所有在Bootstrap类中, 以_init开头的方法, 都会被Yaf调用,
 * @see http://www.php.net/manual/en/class.yaf-bootstrap-abstract.php
 * 这些方法, 都接受一个参数:Yaf_Dispatcher $dispatcher
 * 调用的次序, 和申明的次序相同
 */
class Bootstrap extends Yaf_Bootstrap_Abstract
{

    public function _initConfig()
    {
        // 把配置保存起来
        $arrConfig = Yaf_Application::app()->getConfig();
        Yaf_Registry::set('config', $arrConfig);
    }

    public function _initVendor()
    {
        $config = Yaf_Registry::get("config");
        require $config->application->Vendor->directory . '/autoload.php';
    }

    public function _initLogConfig()
    {
        $config = Yaf_Registry::get("config");
        if (!is_dir($config->application->errorLog->directory)) {
            mkdir($config->application->errorLog->directory, 0766, true);
        }
        ini_set("error_log",
            $config->application->errorLog->directory . DIRECTORY_SEPARATOR . "php_error" . "-" . date("Ymd") . ".log");
    }

    public function _initPlugin(Yaf_Dispatcher $dispatcher)
    {
        //跨域
        $dispatcher->registerPlugin(new CorsPlugin());
        // 注册一个插件
        $objHookPlugin = new HookPlugin();
        $dispatcher->registerPlugin($objHookPlugin);
    }

    public function _initRequest(Yaf_Dispatcher $dispatcher)
    {
        $httpRequest = $dispatcher->getRequest();
        $userAgent = $_SERVER['HTTP_USER_AGENT'];

        if (strpos($userAgent,"Golang async hyena") ===0) {
            $dispatcher->setRequest(new RequestGolangPlugin($httpRequest->getRequestUri(), $httpRequest->getBaseUri()));
        } else {
            $dispatcher->setRequest(new RequestEncryptionPlugin($httpRequest->getRequestUri(), $httpRequest->getBaseUri()));
        }
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher)
    {
        // 在这里注册自己的路由协议,默认使用简单路由
    }

    public function _initView(Yaf_Dispatcher $dispatcher)
    {
        // 在这里注册自己的view控制器，例如smarty,firekylin
        Yaf_Dispatcher::getInstance()->autoRender(false);
    }

    public function _initTideways(Yaf_Dispatcher $dispatcher)
    {
        $env = HhzEnv::getAppEnv();
        $config = Yaf_Registry::get('config');
        if ($config->application->tideways->$env) {
            if (is_dir($config->application->tideways->path) && is_writable($config->application->tideways->path) && function_exists('tideways_xhprof_disable')) {
                list($usec, $sec) = explode(" ", microtime());
                Yaf_Registry::set('startTime', (float)$sec + (float)$usec);// 程序开始时间
                tideways_xhprof_enable();
            }
        }
    }
}
